import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';

export function useChangeTab(activeTab) {
    const router = useRouter();
    const route = useRoute();

    const changeTab = (path) => {
        console.log('尝试跳转到:', path);
        console.log('当前路由表:', router.getRoutes().map(r => r.path));

        // 检查是否为动态路由
        const isDynamicRoute = path.includes('/classDetails/');
        let newPath = path;

        // 提取动态参数 :id（仅对动态路由）
        let id, basePath;
        if (isDynamicRoute) {
            id = path.split('/').pop();
            if (!id || isNaN(id)) {
                console.error('无效的班级 ID:', path);
                ElMessage.error('无效的班级 ID，无法跳转');
                return;
            }
            basePath = path.replace(/\/\d+$/, ''); // 移除 id，得到基路径
            newPath = `${path}/schedule`;
        }

        // 检查路由是否存在
        const routeExists = router.getRoutes().some(r => {
            if (isDynamicRoute) {
                const regex = new RegExp(`^${basePath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/:id(/schedule)?$`);
                return regex.test(r.path);
            }
            return r.path === path;
        });

        if (!routeExists) {
            console.error('目标路由不存在:', path, '路由表:', router.getRoutes().map(r => r.path));
            ElMessage.error('目标页面不存在');
            return;
        }

        activeTab.value = path;
        console.log('切换Tab:', path, '当前路由:', route.path, '路由表:', router.getRoutes().map(r => r.path));
        router.push(newPath).catch(err => {
            if (err.name !== 'NavigationDuplicated') {
                console.error('Tab 跳转失败:', err, '目标路径:', newPath);
                ElMessage.error('跳转失败，请检查路由配置');
            }
        });
    };

    return { changeTab };
}